<?php

namespace common\models\bonus;

use common\models\member\Member;
use Yii;

/**
 * This is the model class for table "{{%bonus}}".
 *
 * @property int $id
 * @property int $member_id 所属会员
 * @property int $bonus_type 奖金类型
 * @property int $from_member_id 来自会员
 * @property string $amount 金额
 * @property int $account_type 账户类型
 * @property int $created_at 时间
 * @property int $pay_at 到账时间
 * @property int $status 状态
 * @property int $bonus_id 上级ID
 * @property string $tax 税
 * @property string $fee 管理费
 * @property string $payment 实发
 */
class Bonus extends \yii\db\ActiveRecord
{

    const STATUS_REBACK = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ISPAY = 1;

    const ACCOUNT_TYPE_MONEY = 0; // 奖金账户类型

    public static $statusArr = [
        self::STATUS_DEFAULT => '未结算',
        self::STATUS_ISPAY => '已结算',
        self::STATUS_REBACK => '异常回收',
    ];

    const BONUS_TASK = 1; // 任务奖励
    const BONUS_REFERRAL = 2; // 分享奖励
    const BONUS_TEAM = 3; // 团队奖励


    public static $typeArr = [
        self::BONUS_TASK => '任务奖励',
        self::BONUS_REFERRAL => '推荐奖励',
        self::BONUS_TEAM => '团队奖励',
    ];

    public $start_time;
    public $end_time;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%bonus}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['member_id', 'bonus_type', 'from_member_id', 'account_type', 'created_at', 'pay_at', 'status', 'bonus_id'], 'integer'],
            [['amount', 'tax', 'fee', 'payment'], 'number'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'member_id' => Yii::t('app', '所属会员'),
            'bonus_type' => Yii::t('app', '奖金类型'),
            'from_member_id' => Yii::t('app', '来自会员'),
            'amount' => Yii::t('app', '金额'),
            'account_type' => Yii::t('app', '账户类型'),
            'created_at' => Yii::t('app', '时间'),
            'pay_at' => Yii::t('app', '到账时间'),
            'status' => Yii::t('app', '状态'),
            'bonus_id' => Yii::t('app', '上级ID'),
            'tax' => Yii::t('app', '税'),
            'fee' => Yii::t('app', '管理费'),
            'payment' => Yii::t('app', '实发'),
        ];
    }

    public static function bonusNameMap($bonus_type = false)
    {
        $typeNameStr = Yii::$app->debris->backendConfig('bonus_type_name', true);
        $res = \explode('|', $typeNameStr);
        if ($bonus_type === false) {
            return $res;
        } else {
            return $res[$bonus_type - 1] ?? '';
        }
    }

    public function getBonusTypeName()
    {
        $typeNameStr = Yii::$app->debris->backendConfig('bonus_type_name', true);
        $arr = \explode('|', $typeNameStr);
        if (isset($arr[$this->bonus_type - 1])) {
            return $arr[$this->bonus_type - 1];
        } else {
            return self::$typeArr[$this->bonus_type] ?? null;
        }
    }

    public function getStatusName()
    {
        return self::$statusArr[$this->status] ?? null;
    }

    //任务奖励
    public static function taskBonus($member, $amount){
        Bonus::addNewBonus(Bonus::BONUS_TASK, $member->id, $amount);
        Bonus::teamBonus($member,$amount);
    }
    //团队奖励
    public static function teamBonus($member, $amount)
    {
        
        $member_task_bonus = Yii::$app->debris->backendConfig('member_task_bonus', true);
        $member_task_bonus_arr  = \explode('|', $member_task_bonus);
        $count = count($member_task_bonus_arr);
        $parents = $member->getAllParents($count);
        $level = $member->current_level;
        $from_member_id = $member->id;
        foreach ($parents as $key => $parent) {
            if ($parent->current_level < $level) {
                continue;
            } else {
                //获得奖金
                $percent = $member_task_bonus_arr[$key];
                $bonus = $amount * $percent / 100;
                Bonus::addNewBonus(Bonus::BONUS_TEAM, $parent->id, $bonus, $from_member_id);
            }
        }
    }

    //推荐奖励
    public static function referralBonus($member,$amount)
    {
        $referral_bonus = Yii::$app->debris->backendConfig('referral_bonus', true);
        $referral_bonus_arr  = \explode('|', $referral_bonus);
        $count = count($referral_bonus_arr);
        $parents = $member->getAllParents($count);
        $level = $member->current_level;
        $from_member_id = $member->id;
        foreach ($parents as $key => $parent) {
            if($parent->current_level < $level){
                continue;
            }else{
                //获得奖金
                $percent = $referral_bonus_arr[$key];
                $bonus = $amount * $percent /100;
                Bonus:: addNewBonus(Bonus::BONUS_REFERRAL, $parent->id, $bonus,$from_member_id);
            }
        }
    }

    public static function addNewBonus($type, $member_id, $amount, $from_member_id = 0, $accountType = null)
    {
        if ($accountType === null) {
            $accountType = self::ACCOUNT_TYPE_MONEY;
        }
        $model = new self;
        $model->member_id = $member_id;
        $model->bonus_type = $type;
        $model->amount = $amount;
        $model->created_at = time();
        $model->status = self::STATUS_DEFAULT;
        $model->account_type = $accountType;
        if ($from_member_id) {
            $model->from_member_id = $from_member_id;
        } else {
            $model->from_member_id = $member_id;
        }
        if (!$model->save()) {
            throw new \Exception('奖金保存失败', 1);
        }
        Yii::$app->queue->push(new \common\queues\BonusJob(['id' => $model->id]));
        return true;
    }

    public function getMember()
    {
        return $this->hasOne(Member::class, ['id' => 'member_id']);
    }

    public function getFromMember()
    {
        return $this->hasOne(Member::class, ['id' => 'from_member_id']);
    }
}
